package com.pf.controller;

import com.github.tobato.fastdfs.domain.FileInfo;
import com.github.tobato.fastdfs.domain.MetaData;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.Set;

/**
 * FastDFS 文件上传、下载、查看、删除
 *
 * @author PanFei
 * @version 1.0.0
 * @createTime 2021/12/12 20:34
 */
@RestController
@RequestMapping("/fastdfs")
public class FastDFSController {

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    /**
     * 文件上传
     *
     * @return
     */
    @GetMapping("/upload")
    public String uploadFile() {
        InputStream inputStream = null;
        try {
            File file = new File("D:\\test\\测试文件.txt");
            inputStream = new FileInputStream(file);
            Set<MetaData> metaDataSet = new HashSet<>();
            metaDataSet.add(new MetaData("originFileName", "测试文件.txt"));
            StorePath storePath = fastFileStorageClient.uploadFile(inputStream, file.length(), "txt", metaDataSet);
            // 获取上传后的路径
            String fullPath = storePath.getFullPath();
            return fullPath;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 下载文件
     * <p>
     * 访问示例：
     * http://localhost:8080/fastdfs/downloadFile?filePath=group1/M00/00/00/wKhOgmG1v4GAFHOBAAAAFrFnoaw260.txt
     *
     * @param filePath
     */
    @GetMapping("/downloadFile")
    public void downloadFile(@RequestParam("filePath") String filePath,
                             HttpServletResponse response) {

        String groupName = filePath.substring(0, filePath.indexOf("/"));
        String path = filePath.substring(filePath.indexOf("/") + 1);

        byte[] bytes = fastFileStorageClient.downloadFile(groupName, path, new DownloadByteArray());
        try {
            // Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            // attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("测试.txt", "UTF-8"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", bytes.length + "");
            response.setContentType("application/octet-stream");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


        // 输出文件
        // 方式1
        InputStream inputStream = null;
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            // 字节转为输入流
            inputStream = new ByteArrayInputStream(bytes);
            byte[] buffer = new byte[1024];
            int length = 0;
            while (-1 != (length = inputStream.read(buffer))) {
                outputStream.write(buffer, 0, length);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        // 方式2：直接通过输出流一次性输出字节
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取设置的文件元数据（对应上传文件的  Set<MetaData> metaDataSet 信息）
     *
     * @param filePath
     * @return
     */
    @GetMapping("/getMetadata")
    public Set<MetaData> getMetadata(@RequestParam("filePath") String filePath) {
        String groupName = filePath.substring(0, filePath.indexOf("/"));
        String path = filePath.substring(filePath.indexOf("/") + 1);
        Set<MetaData> metadata = fastFileStorageClient.getMetadata(groupName, path);
        return metadata;
    }


    /**
     * 查看文件信息
     *
     * @param filePath
     * @return
     */
    @GetMapping("/queryFileInfo")
    public FileInfo queryFileInfo(@RequestParam("filePath") String filePath) {
        String groupName = filePath.substring(0, filePath.indexOf("/"));
        String path = filePath.substring(filePath.indexOf("/") + 1);
        FileInfo fileInfo = fastFileStorageClient.queryFileInfo(groupName, path);
        return fileInfo;
    }

    /**
     * 删除文件
     *
     * @param filePath
     */
    @GetMapping("/deleteFile")
    public void deleteFile(@RequestParam("filePath") String filePath) {
        String groupName = filePath.substring(0, filePath.indexOf("/"));
        String path = filePath.substring(filePath.indexOf("/") + 1);
        fastFileStorageClient.deleteFile(groupName, path);
        System.out.println(">>>>> 已删除");
    }

}
